package com.ghostmonk.utils
{
	import caurina.transitions.*;
	import caurina.transitions.properties.DisplayShortcuts;
	
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;

	public class SiteLoader extends Sprite
	{
		
		private var _preloader:MovieClip;
		private var _mainLoader:Loader;
		
		public function SiteLoader(url:String, preloader:MovieClip)
		{	
			DisplayShortcuts.init();
			
			_preloader = preloader;
			_mainLoader = new Loader();
			_preloader.stop();
			
			_preloader.alpha = 0;
			
			_mainLoader.contentLoaderInfo.addEventListener(Event.OPEN, onOpen);
			_mainLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onProgress);
			_mainLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);			
			_mainLoader.load(new URLRequest(url));
		}
		
		private function onOpen(e:Event):void 
		{
		  	addChild(_preloader);
			Tweener.addTween(_preloader, {alpha:1, time:0.5});
		}
		
		private function onProgress(e:ProgressEvent):void {
			var percent:Number = e.bytesTotal != 0 ? e.bytesLoaded / e.bytesTotal : 0;
			_preloader.goToAndStop = Math.ceil(percent * 100);
		}
		
		private function onComplete(e:Event):void 
		{
			Tweener.addTween(_preloader, {alpha:0, time:0.5, onComplete:showContent});
			dispatchEvent(e);
		}
		
		private function showContent():void
		{
			removeChild(_preloader);
			addChild(_mainLoader);
		}
		
		public function postionProgressBar(xPos:Number, yPos:Number):void
		{
			_preloader.x = xPos;
			_preloader.y = xPos;
		}
				
	}
}